#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
污染类型数据模型
定义系统中的污染类型、关系和样例模型
"""

from sqlalchemy import Column, Integer, String, Text, Boolean, ForeignKey, DateTime, FLOAT
from sqlalchemy.orm import relationship
from sqlalchemy.sql import func
from typing import Dict, Any, List, Optional
import enum
from models.base import Base

default_customer = "default"

class PollutionTypeLevel(str, enum.Enum):
    """污染类型层级枚举"""
    LEVEL_1 = "1"  # 一级分类
    LEVEL_2 = "2"  # 二级分类
    LEVEL_3 = "3"  # 三级分类


class PollutionType(Base):
    """污染类型模型"""
    
    __tablename__ = "pollution_types"
    
    # 主键和基本信息
    id = Column(Integer, primary_key=True)
    customer_id = Column(String(50), nullable=False, comment="客户标识")
    code = Column(String(20), nullable=False, comment="污染类型代码")
    name = Column(String(100), nullable=False, comment="污染类型名称")
    parent_code = Column(String(20), comment="父级类型代码")
    level = Column(Integer, default=1, comment="层级深度")
    
    # 标签信息
    tag_name = Column(String(100), comment="标签名称")
    tag_category = Column(String(50), comment="标签分类")
    usage_scope = Column(Text, comment="适用范围")
    exclusion_scope = Column(Text, comment="排除范围")
    display_name = Column(String(100), comment="显示名称")
    parent_tag_code = Column(String(20), comment="父级标签代码")
    
    # 管理字段
    sort_order = Column(Integer, default=0, comment="排序顺序")
    description = Column(Text, comment="详细说明")
    is_active = Column(Boolean, default=True, comment="是否激活")
    is_system = Column(Boolean, default=False, comment="是否系统类型")
    
    # 时间戳
    created_at = Column(DateTime, default=func.now(), comment="创建时间")
    updated_at = Column(DateTime, default=func.now(), onupdate=func.now(), comment="更新时间")
    
    # 关联关系
    examples = relationship("PollutionTypeExample", back_populates="pollution_type", cascade="all, delete-orphan")
    
    def to_dict(self, include_examples_count: bool = True, db_session=None) -> Dict[str, Any]:
        """转换为字典"""
        result = {
            "id": self.id,
            "customer_id": self.customer_id,
            "code": self.code,
            "name": self.name,
            "parent_code": self.parent_code,
            "level": self.level,
            "tag_name": self.tag_name,
            "tag_category": self.tag_category,
            "usage_scope": self.usage_scope,
            "exclusion_scope": self.exclusion_scope,
            "display_name": self.display_name,
            "parent_tag_code": self.parent_tag_code,
            "sort_order": self.sort_order,
            "description": self.description,
            "is_active": self.is_active,
            "is_system": self.is_system,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None,
        }

        # 可选的样例计数，避免延迟加载问题
        if include_examples_count:
            # 优先使用传入的数据库会话，避免创建新会话导致冲突
            if db_session is not None:
                try:
                    count = db_session.query(PollutionTypeExample).filter(
                        PollutionTypeExample.pollution_type_id == self.id
                    ).count()
                    result["examples_count"] = count
                except:
                    result["examples_count"] = 0
            else:
                # 只有在没有传入会话时才创建新会话
                from core.database import get_db_session
                try:
                    with get_db_session() as db:
                        count = db.query(PollutionTypeExample).filter(
                            PollutionTypeExample.pollution_type_id == self.id
                        ).count()
                        result["examples_count"] = count
                except:
                    result["examples_count"] = 0

        return result
    
    def get_hierarchy_path(self) -> str:
        """获取层级路径"""
        from core.database import get_db_session
        if self.parent_code:
            with get_db_session() as db:
                # 递归获取父级路径（相同客户内）
                parent = db.query(PollutionType).filter(
                    PollutionType.customer_id == self.customer_id,
                    PollutionType.code == self.parent_code,
                    PollutionType.is_active == True
                ).first()
                if parent:
                    return f"{parent.get_hierarchy_path()} > {self.name}"
        return self.name
    
    def get_all_children_codes(self) -> List[str]:
        """获取所有子级类型代码（相同客户内）"""
        from core.database import get_db_session
        with get_db_session() as db:
            all_children = []
            children = db.query(PollutionType).filter(
                PollutionType.customer_id == self.customer_id,
                PollutionType.parent_code == self.code,
                PollutionType.is_active == True
            ).all()
            
            for child in children:
                all_children.append(child.code)
                all_children.extend(child.get_all_children_codes())
            
            return all_children


class PollutionTypeExample(Base):
    """污染类型样例模型"""
    
    __tablename__ = "pollution_type_examples"
    
    id = Column(Integer, primary_key=True)
    customer_id = Column(String(50), nullable=False, comment="客户标识")
    pollution_type_id = Column(Integer, ForeignKey("pollution_types.id", ondelete="CASCADE"), nullable=False, comment="污染类型ID")
    example_content = Column(Text, nullable=False, comment="样例内容")
    judgment_basis = Column(Text, comment="判断依据")
    keywords = Column(Text, comment="关键词（逗号分隔）")
    confidence_level = Column(FLOAT, default=0.8, comment="置信度")
    is_active = Column(Boolean, default=True, comment="是否激活")
    created_at = Column(DateTime, default=func.now(), comment="创建时间")
    updated_at = Column(DateTime, default=func.now(), onupdate=func.now(), comment="更新时间")
    
    # 外键关系
    pollution_type = relationship("PollutionType", back_populates="examples")
    
    def to_dict(self) -> Dict[str, Any]:
        """转换为字典"""
        result = {
            "id": self.id,
            "customer_id": self.customer_id,
            "pollution_type_id": self.pollution_type_id,
            "example_content": self.example_content,
            "judgment_basis": self.judgment_basis,
            "keywords": self.keywords.split(",") if self.keywords else [],
            "confidence_level": self.confidence_level,
            "is_active": self.is_active,
            "created_at": self.created_at.isoformat() if self.created_at else None,
            "updated_at": self.updated_at.isoformat() if self.updated_at else None,
        }

        # 避免延迟加载，不直接访问关系属性
        # 如果需要污染类型名称，应该在服务层通过查询获取
        return result
    
    def get_keywords_list(self) -> List[str]:
        """获取关键词列表"""
        if not self.keywords:
            return []
        return [keyword.strip() for keyword in self.keywords.split(",") if keyword.strip()]